﻿// based on http://dotnetbyexample.blogspot.com/2011/03/simple-windows-phone-7-silverlight.html
// by Joost van Schaik 
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace Outcoder.UI.Xaml
{
	/* TODO: [DV] Comment. */
	public static class StoryboardExtensionsForSilverlight
	{
		public static void AddAnimation(this Storyboard storyboard,
			DependencyObject dependencyObject,
			DependencyProperty targetProperty,
			Timeline timeline)
		{
			ArgumentValidator.AssertNotNull(storyboard, "storyboard");
			ArgumentValidator.AssertNotNull(dependencyObject, "dependencyObject");
			ArgumentValidator.AssertNotNull(targetProperty, "targetProperty");

			Storyboard.SetTarget(timeline, dependencyObject);
			Storyboard.SetTargetProperty(timeline, new PropertyPath(targetProperty));
			storyboard.Children.Add(timeline);
		}

		public static void AddTranslationAnimation(this Storyboard storyboard,
			FrameworkElement frameworkElement,
			Point fromPoint,
			Point toPoint,
			Duration duration)
		{
			ArgumentValidator.AssertNotNull(storyboard, "storyboard");
			ArgumentValidator.AssertNotNull(frameworkElement, "frameworkElement");

			storyboard.AddTranslationAnimation(
				frameworkElement, fromPoint, toPoint, duration, null);
		}

		public static void AddTranslationAnimation(this Storyboard storyboard,
			FrameworkElement targetElement,
			Point fromPoint,
			Point toPoint,
			Duration duration,
			IEasingFunction easingFunction)
		{
			ArgumentValidator.AssertNotNull(storyboard, "storyboard");
			ArgumentValidator.AssertNotNull(targetElement, "targetElement");

			var xAnimation = storyboard.CreateDoubleAnimation(
								duration, fromPoint.X, toPoint.X, easingFunction);

			var yAnimation = storyboard.CreateDoubleAnimation(
								duration, fromPoint.Y, toPoint.Y, easingFunction);

			storyboard.AddAnimation(
				targetElement.RenderTransform,
				CompositeTransform.TranslateXProperty,
				xAnimation);

			storyboard.AddAnimation(
				targetElement.RenderTransform,
				CompositeTransform.TranslateYProperty,
				yAnimation);
		}

		public static Timeline CreateDoubleAnimation(this Storyboard storyboard,
			Duration duration,
			double from,
			double to)
		{
			ArgumentValidator.AssertNotNull(storyboard, "storyboard");

			SineEase sineEase = new SineEase { EasingMode = EasingMode.EaseInOut };
			return storyboard.CreateDoubleAnimation(duration, from, to, sineEase);
		}

		public static Timeline CreateDoubleAnimation(this Storyboard storyboard,
			Duration duration,
			double from,
			double to,
			IEasingFunction easingFunction)
		{
			ArgumentValidator.AssertNotNull(storyboard, "storyboard");

			var result = new DoubleAnimation
			{
				From = from,
				To = to,
				Duration = duration,
				EasingFunction = easingFunction
			};

			return result;
		}
	}
}
